<template>
  <div class="container" style="margin-top: 150px">
    <div class="main-box">
      <div :class="['container2', 'container-register', { 'is-txl': isLogin }]">
        <div class="form">
          <h2 class="title">Create Account</h2>
          <span class="text">use email for registration</span>
          <el-alert
            v-show="registerErr"
            :title="registerTitle"
            type="error"
            show-icon :closable="false">
          </el-alert>
          <input class="form__input" v-model="nemail" type="email" placeholder="Email"/>
          <el-alert
            v-show="nemailErr"
            title="邮箱格式错误"
            type="error"
            show-icon :closable="false">
          </el-alert>
          <el-row style="width: 100%;margin-left: 165px" :gutter="40">
            <el-col :span="11">
              <input class="form__input" placeholder="邮箱验证码" v-model="emailAuthCode"/>
            </el-col>
            <el-col :span="8">
              <button :disabled="btnBoolean" class="login-btn" @click="handleSendAuthCode(nemail)"><span
                style="font-size: 20px;color: rgb(212,212,212)">|&nbsp;&nbsp;</span>{{ sendEmailBtn }}
              </button>
            </el-col>
          </el-row>
          <input class="form__input" type="text" v-model="nusername" placeholder="用户名"/>
          <input class="form__input" v-model="nnickName" type="text" placeholder="昵称"/>
          <input class="form__input" v-model="npassword" type="password" placeholder="密码:6-12位英文、数字、下划线"/>
          <el-alert
            v-show="npasswordErr"
            title="密码错误"
            type="error"
            show-icon :closable="false">
          </el-alert>
          <input class="form__input" v-model="npassword2" type="password" placeholder="确认密码"
                 @keyup.enter="registerEnterFun"/>
          <el-alert
            v-show="npassword2Err"
            title="两次输入密码不一致"
            type="error"
            show-icon :closable="false">
          </el-alert>
          <div class="primary-btn" @click="newRegister">立即注册</div>
        </div>
      </div>
      <div
        :class="['container2', 'container-login', { 'is-txl is-z200': isLogin }]"
      >
        <div class="form" v-if="!isForget">
          <h2 class="title">Sign in to Zlwblog</h2>
          <span class="text">or use email for registration</span>
          <el-alert
            v-show="loginErr"
            :title="loginTitle"
            type="error"
            show-icon :closable="false">
          </el-alert>
          <input class="form__input" v-model="username" type="text" placeholder="User Name"/>
          <input class="form__input" v-model="password" @keyup.enter="loginEnterFun" type="password"
                 placeholder="Password"/>
          <span @click="isForget = !isForget"
                style="cursor: url(https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/img/pointer.cur), pointer;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            forget password?</span>
          <div class="primary-btn" @click="gotoHome">立即登录</div>
        </div>
        <!--  忘记密码  -->
        <div class="form" v-else>
          <h2 class="title">Recover Your Password</h2>
          <span class="text">or use email for registration</span>
          <input class="form__input" v-model="email" type="email" placeholder="Email"/>
          <el-alert
            v-show="emailErr"
            title="邮箱格式错误"
            type="error"
            show-icon :closable="false">
          </el-alert>
          <el-row style="width: 100%;margin-left: 165px" :gutter="40">
            <el-col :span="11">
              <input class="form__input" placeholder="Auth Code" v-model="emailAuthCode2"/>
            </el-col>
            <el-col :span="8">
              <button :disabled="btnBoolean2" class="login-btn" @click="handleSendAuthCode2(email)"><span
                style="font-size: 20px;color: rgb(212,212,212)">|&nbsp;&nbsp;</span>{{ sendEmailBtn2 }}
              </button>
            </el-col>
          </el-row>
          <input class="form__input" v-model="newPassword" @keyup.enter="forgetPwdEnterFun" type="password"
                 placeholder="New Password"/>
          <el-alert
            v-show="newPasswordErr"
            title="密码错误"
            type="error"
            show-icon :closable="false">
          </el-alert>
          <span @click="isForget = !isForget"
                style="cursor: url(https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/img/pointer.cur), pointer;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            Return to Login<i class="fa fa-reply"></i></span>
          <div class="primary-btn" @click="forgetPwd">确定</div>
        </div>
      </div>
      <div :class="['switch', { login: isLogin }]">
        <div class="switch__circle"></div>
        <div class="switch__circle switch__circle_top"></div>
        <div class="switch__container">
          <h2>{{ isLogin ? 'Hello Friend !' : 'Welcome Back !' }}</h2>
          <p>
            {{
              isLogin
                ? 'Enter your personal details and start journey with me'
                : 'To keep connected with Zlwblog please login with your personal info'
            }}
          </p>
          <div class="primary-btn" @click="isLogin = !isLogin">
            {{ isLogin ? '立即注册' : '立即登录' }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getEmailAuthCode, userLogin, userRegister, forgetPassword} from '../api/user.js'
import {setToken} from '../utils/auth.js'

export default {
  name: 'Login',
  data() { //选项 / 数据
    return {
      isForget: false,
      dialogVisible: false,//忘记密码弹出框
      sendEmailBtn: "获取验证码",
      sendEmailBtn2: "获取验证码",
      btnBoolean: false,
      btnBoolean2: false,
      countDown: null,
      countDown2: null,
      EmailTimer: null,
      EmailTimer2: null,
      username: '',//用户名
      email: '',//邮箱
      password: '',//密码
      nusername: '',//新用户注册名
      newPassword: '',//新密码
      nnickName: '',//新用户昵称
      nemail: '',//新用户注册邮箱
      emailAuthCode: '',//邮箱验证码
      emailAuthCode2: '',//忘记密码邮箱验证码
      npassword: '',//新用户注册密码
      npassword2: '',//新用户注册重复密码
      isLogin: true,//是否已经登录
      loginErr: false,//登录错误
      loginTitle: '用户名或密码错误',
      nusernameErr: false,//新用户注册用户名错误
      nemailErr: false,//新用户注册邮箱错误
      emailErr: false,//忘记密码邮箱错误
      npasswordErr: false,//新用户注册密码错误
      npassword2Err: false,//新用户注册重复密码错误
      newPasswordErr: false,//新密码错误
      registerErr: false,//已注册错误
      registerTitle: '该邮箱已注册',
      step: 1,//忘记密码进度
      fullscreenLoading: false,//全屏loading
      urlstate: 0,//重新注册
      userInfo: {}
    }
  },
  methods: {
    reset() {
      this.nemail = '';
      this.emailAuthCode = '';
      this.npassword = '';
      this.npassword2 = '';
      this.nnickName = '';
      this.nusername = '';
      this.countDown2 = null;
      this.EmailTimer2 = null;
      this.btnBoolean2 = false;
      this.sendEmailBtn2 = "获取验证码";
    },
    reset2() {
      this.email = '';
      this.newPassword = '';
      this.emailAuthCode2 = '';
      this.countDown2 = '';
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    /* 发送邮箱验证码 */
    handleSendAuthCode(email) {
      getEmailAuthCode(email).then(() => {
        this.countDown = 60;
        this.$message.success("发送成功请注意查收")
        this.btnBoolean = true;
        this.sendEmailBtn = "重新获取(" + this.countDown + ")"
        this.EmailTimer = setInterval(() => {
          if (this.countDown == 1) {
            clearInterval(this.EmailTimer)
            this.sendEmailBtn = "重新获取";
            this.btnBoolean = false;
            return;
          }
          this.countDown--;
          this.sendEmailBtn = "重新获取(" + this.countDown + ")";
        }, 1000);
      })
    },
    /* 发送邮箱验证码（忘记密码） */
    handleSendAuthCode2(email) {
      getEmailAuthCode(email).then(() => {
        this.countDown2 = 60;
        this.$message.success("发送成功请注意查收")
        this.btnBoolean2 = true;
        this.sendEmailBtn2 = "重新获取(" + this.countDown2 + ")"
        this.EmailTimer2 = setInterval(() => {
          if (this.countDown2 == 1) {
            clearInterval(this.EmailTimer2)
            this.sendEmailBtn2 = "重新获取";
            this.btnBoolean2 = false;
            return;
          }
          this.countDown2--;
          this.sendEmailBtn2 = "重新获取(" + this.countDown2 + ")";
        }, 1000);
      })
    },
    //事件处理器
    routeChange: function () {
      var that = this;
      that.login = that.$route.query.login == undefined ? 1 : parseInt(that.$route.query.login);//获取传参的login
      that.urlstate = that.$route.query.urlstate == undefined ? 0 : that.$route.query.urlstate;//获取传参的usrlstate状态码
      // console.log(that.login,that.urlstate);

    },

    loginEnterFun: function (e) {
      var keyCode = window.event ? e.keyCode : e.which;
      // console.log('回车登录',keyCode,e);
      if (keyCode == 13) {
        this.gotoHome();
      }
    },
    gotoHome: function () {//用户登录
      const loading = this.$loading({});
      userLogin(this.username, this.password).then((response) => {
        // 登录成功记录token和用户信息，登录失败给对应提示
        setToken(response.token)
        // 存储用户信息
        localStorage.setItem("userInfo", JSON.stringify(response.userInfo))
        if (localStorage.getItem('logUrl')) {
          this.$router.push({path: localStorage.getItem('logUrl')});
        } else {
          this.$router.push({path: '/'});
        }
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          loading.close();
        });
        this.$message.success('登录成功！');
      }).catch((res) => {
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          loading.close();
        });
        let errorMsg = res.toString()
        if (errorMsg.startsWith("Error:"))
          this.$notify.error(errorMsg)
      })

    },
    forgetPwdEnterFun: function (e) {
      var keyCode = window.event ? e.keyCode : e.which;
      // console.log('回车登录',keyCode,e);
      if (keyCode == 13) {
        this.forgetPwd();
      }
    },
    forgetPwd: function () {//忘记密码提交
      var that = this;
      var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      var preg = /^(\w){6,12}$/;
      if (reg.test(that.email)) {
        that.emailErr = false;
      } else {
        that.emailErr = true;
      }
      if (that.newPassword && preg.test(that.newPassword)) {
        that.newPasswordErr = false;
      } else {
        that.newPasswordErr = true;
      }
      if (!that.emailErr && !that.newPasswordErr) {
        that.fullscreenLoading = true;
        const loading = this.$loading({});
        forgetPassword(that.email, that.emailAuthCode2, that.newPassword).then((response) => {
          this.$message.success("密码修改成功")
          //修改成功后清空表单
          this.reset2()
          this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            loading.close();
          });
        }).catch((error) => {
          that.fullscreenLoading = false;
          this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            loading.close();
          });
        })
      }
    },

    registerEnterFun: function (e) {
      var keyCode = window.event ? e.keyCode : e.which;
      // console.log('回车注册',keyCode,e);
      if (keyCode == 13) {
        this.newRegister();
      }
    },
    newRegister: function () {//注册提交
      var that = this;
      var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      var preg = /^(\w){6,12}$/;
      if (that.nusername) {
        that.nusernameErr = false;
      } else {
        that.nusernameErr = true;
      }
      if (reg.test(that.nemail)) {
        that.nemailErr = false;
      } else {
        that.nemailErr = true;
      }
      if (that.npassword && preg.test(that.npassword)) {
        that.npasswordErr = false;
      } else {
        that.npasswordErr = true;
      }
      if (that.npassword == that.npassword2) {
        that.npassword2Err = false;
      } else {
        that.npassword2Err = true;
        return
      }
      if (!that.nusernameErr && !that.nemailErr && !that.npasswordErr) {
        const loading = this.$loading({});
        userRegister(that.nusername, that.nnickName, that.nemail, that.npassword, that.npassword2, that.emailAuthCode).then((response) => {
          this.$message.success("注册成功,快去登录吧!")
          // 注册成功清空表单
          this.reset()
          this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            loading.close();
          });
        }).catch((error) => {
          that.fullscreenLoading = false;
          this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            loading.close();
          });
        })
      }
    },
    goLogin: function () {//去登陆
      this.$router.push({path: '/Login?login=1'});
    },
    goRegister: function () {//去注册
      this.$router.push({path: '/Login?login=0'});
    }

  }
  ,
  components: { //定义组件

  }
  ,
  watch: {
    // 如果路由有变化，会再次执行该方法
    '$route':
      'routeChange'
  }
  ,
  created() { //生命周期函数
    var that = this;
    that.routeChange();
  }
}
</script>

<style scoped>
.el-alert {
  width: 375px !important;
}

button[disabled] {
  color: rgb(179, 167, 170) !important;
}

.login-btn {
  width: 100px;
  height: 40px;
  margin: 4px 0;
  font-size: 13px;
  letter-spacing: 0.15px;
  border: none;
  outline: none;
  color: rgb(75, 112, 226);
  background: rgb(0, 0, 0, 0);
  cursor: url(https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/img/pointer.cur), pointer;
}

.main-box {
  position: relative;
  width: 1000px;
  min-width: 1000px;
  min-height: 600px;
  height: 600px;
  padding: 25px;
  background-color: #ecf0f3;
  box-shadow: 10px 10px 10px #d1d9e6, -10px -10px 10px #f9f9f9;
  border-radius: 12px;
  overflow: hidden;
}

.container2 {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  width: 600px;
  height: 100%;
  padding: 25px;
  background-color: #ecf0f3;
  transition: all 1.25s;
}

.form {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100%;
  color: #a0a5a8;
}

.title {
  font-size: 34px;
  font-weight: 700;
  line-height: 3;
  color: #181818;
}

.text {
  margin-top: 30px;
  margin-bottom: 12px;
}

.form__input {
  width: 350px;
  height: 40px;
  margin: 4px 0;
  padding-left: 25px;
  font-size: 13px;
  letter-spacing: 0.15px;
  border: none;
  outline: none;
// font-family: 'Montserrat', sans-serif; background-color: #ecf0f3; transition: 0.25s ease; border-radius: 8px; box-shadow: inset 2px 2px 4px #d1d9e6, inset -2px -2px 4px #f9f9f9;
}

&::placeholder {
  color: #a0a5a8;
}


.container-register {
  z-index: 100;
  left: calc(100% - 600px);
}

.container-login {
  left: calc(100% - 600px);
  z-index: 0;
}

.is-txl {
  left: 0;
  transition: 1.25s;
  transform-origin: right;
}

.is-z200 {
  z-index: 200;
  transition: 1.25s;
}

.switch {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 300px;
  padding: 50px;
  z-index: 200;
  transition: 1.25s;
  background-color: #ecf0f3;
  overflow: hidden;
  box-shadow: 4px 4px 10px #d1d9e6, -4px -4px 10px #f9f9f9;
  color: #a0a5a8;
}

.switch__circle {
  position: absolute;
  width: 500px;
  height: 500px;
  border-radius: 50%;
  background-color: #ecf0f3;
  box-shadow: inset 8px 8px 12px #d1d9e6, inset -8px -8px 12px #f9f9f9;
  bottom: -60%;
  left: -60%;
  transition: 1.25s;
}

.switch__circle_top {
  top: -30%;
  left: 60%;
  width: 300px;
  height: 300px;
}

.switch__container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: absolute;
  width: 400px;
  padding: 50px 55px;
  transition: 1.25s;
}

h2 {
  font-size: 34px;
  font-weight: 700;
  line-height: 3;
  color: #181818;
}

p {
  font-size: 14px;
  letter-spacing: 0.25px;
  text-align: center;
  line-height: 1.6;
}


.login {
  left: calc(100% - 400px);
}

.switch__circle {
  left: 0;
}

.primary-btn {
  width: 180px;
  height: 50px;
  border-radius: 25px;
  margin-top: 50px;
  text-align: center;
  line-height: 50px;
  font-size: 14px;
  letter-spacing: 2px;
  background-color: #4b70e2;
  color: #f9f9f9;
  cursor: pointer;
  box-shadow: 8px 8px 16px #d1d9e6, -8px -8px 16px #f9f9f9;
}

.primary-btn:hover {
  cursor: url(https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/img/pointer.cur), pointer;
  box-shadow: 4px 4px 6px 0 rgb(255 255 255 / 50%),
  -4px -4px 6px 0 rgb(116 125 136 / 50%),
  inset -4px -4px 6px 0 rgb(255 255 255 / 20%),
  inset 4px 4px 6px 0 rgb(0 0 0 / 40%);
}
</style>

